package com.platform.api;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.config.IntegralType;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.*;
import com.platform.util.wechat.CheckUtil;
import com.platform.utils.EmojiUtils;
import com.platform.utils.Query;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.RequestWrapper;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/posts")
public class ApiPostsController extends ApiBaseAction {

    @Autowired
    private ApiPostsService postsService;
    @Autowired
    private ApiPostsCommentService postsCommentService;
    @Autowired
    private ApiPostsPictureService postsPictureService;
    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiCollectService collectService;
    @Autowired
    private ApiLikeRecordService likeRecordService;
    @Autowired
    private ApiSysMacroService macroService;
    @Autowired
    private ApiUserIntegralService userIntegralService;


    /**
     * @param loginUser
     * @param page
     * @param size
     * @param type      0-温暖(默认)；1-推荐；2-热门；3-收藏
     * @return
     */
    @RequestMapping(value = "list", method = {RequestMethod.GET, RequestMethod.POST})
    public Object list(@LoginUser UserVo loginUser,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size,
                       @RequestParam(value = "type", defaultValue = "0") Integer type) {
        Long userId = loginUser.getUserId();
        Map<String, Object> param = new HashMap<>();
        param.put("page", page);
        param.put("limit", size);
        if (type == 1) {
            param.put("isRecommend", 1);//是否推荐：0-否；1-是
        } else if (type == 2) {
            param.put("isHot", 1);//是否热门：0-否；1-是
        } else if (type == 3) {//收藏列表
            param.put("userId", userId);
            param.put("typeId", 2);//收藏类型：0-商品收藏；1-暖课；2-社区故事(帖子)
        }

        param.put("status", 1);//是否被管理员批准显示;1是;0未批准显示
        param.put("sidx", "id");
        param.put("order", "desc");

        Query query = new Query(param);
        List<PostsVo> postsVos = postsService.queryList(query);

        if (postsVos.size() > 0) {
            for (PostsVo postsVo : postsVos) {

                //todo 处理用户信息显示
                UserVo postsUserVo = userService.queryObject((long) postsVo.getUserId());
                postsVo.setUserInfo(postsUserVo);

                //todo 处理评论数
                Map<String, Object> para = new HashMap<>();
                para.put("postId", postsVo.getId());
                para.put("status", 1);
                para.put("sidx", "id");
                para.put("order", "desc");
                List<PostsCommentVo> postsCommentVos = postsCommentService.queryList(para);
                int commentCount = postsCommentVos.size();
                postsVo.setCommentCount(commentCount);

                //todo 处理最新一条评论
                if (commentCount > 0) {
                    PostsCommentVo postsCommentVo = postsCommentVos.get(0);
                    //相对时间
                    postsCommentVo.setRelativeDate(RelativeDateFormat.format(postsCommentVo.getAddTime()));
                    //评论者的信息
                    UserVo commentUserVo = userService.queryObject((long) postsCommentVo.getUserId());
                    postsCommentVo.setUserInfo(commentUserVo);
                    //处理emoji
                    postsCommentVo.setContentDesc(EmojiUtils.emojiRecovery2(postsCommentVo.getContentDesc()));
                    postsVo.setPostsCommentVo(postsCommentVo);
                }

                //todo 处理相对时间显示
                postsVo.setRelativeDate(RelativeDateFormat.format(postsVo.getAddTime()));

                //todo 是否已经收藏
                Boolean collected = collectService.isCollected(2, postsVo.getId(), userId);
                if (collected) {
                    postsVo.setIsCollected(1);
                }
                //todo 是否已经点赞
                Boolean liked = likeRecordService.isLiked(0, postsVo.getId(), userId);
                if (liked) {
                    postsVo.setIsLiked(1);
                }

                //todo 图片/视频列表
                Map<String, Object> params = new HashMap<>();
                params.put("postId", postsVo.getId());
                params.put("sidx", "sort_order");
                params.put("order", "asc");
                List<PostsPictureVo> postsPictureVos = postsPictureService.queryList(params);
                //todo 资源类型
                if (postsPictureVos.size() > 0) {
                    PostsPictureVo postsPictureVo = postsPictureVos.get(0);
                    postsVo.setResourceType(postsPictureVo.getUrlType());
                }

                postsVo.setPostsPictureVos(postsPictureVos);
            }
        }

        int total = postsService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(postsVos, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }


    @IgnoreAuth
    @RequestMapping(value = "getIp", method = {RequestMethod.GET, RequestMethod.POST})
    public Object getIp(String ip) {
        String city = BaiduIpUtil.getCity(ip);
        return toResponsSuccess(city);
    }


    @RequestMapping(value = "add", method = {RequestMethod.GET, RequestMethod.POST})
    public Object add(@LoginUser UserVo loginUser) throws UnsupportedEncodingException {
        JSONObject jsonParam = getJsonRequest();
        if (Validator.isEmpty(jsonParam)) {
            return toResponsFail("请提供参数内容");
        }
        Long userId = loginUser.getUserId();
        String title = jsonParam.getString("title");
        String content = jsonParam.getString("content");
        JSONArray imagesList = jsonParam.getJSONArray("imagesList");
        //是否置顶：0-申请；1-同意；2-不置顶
        Integer isTop = jsonParam.getInteger("isTop");
        String videoCoverUrl = jsonParam.getString("videoCoverUrl");

        //todo 校验参数是否为空
        if (Validator.isEmpty(title)) {
            return toResponsFail("请输入您要发布的主题");
        }
        if (Validator.isEmpty(content)) {
            return toResponsFail("请输入您要发布的内容");
        }
        if (Validator.isEmpty(isTop)) {
            return toResponsFail("请选择是否申请置顶");
        }
        if (!Validator.isNumber(isTop.toString())) {
            return toResponsFail("申请置顶为数字类型");
        }

        //todo 校验参数长度
        if (title.length() > 150) {
            return toResponsFail("主题不能超过150个字符");
        }
        if (content.length() > 1500) {
            return toResponsFail("内容不能超过1500个字符");
        }
        if (imagesList != null && imagesList.size() > 9) {
            return toResponsFail("图片不能超过9张");
        }

        PostsVo postsVo = new PostsVo();
        postsVo.setUserId(userId.intValue());
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        } else {
            String[] split = ip.split(",");
            ip = split[0];
        }
        postsVo.setIp(ip);
        postsVo.setViewCount(0);
        postsVo.setCollectCount(0);
        postsVo.setTitle(EmojiUtils.emojiConvert1(title));
        postsVo.setContentDesc(EmojiUtils.emojiConvert1(content));
        postsVo.setIsTop(isTop);
        postsVo.setLikeCount(0);
        postsVo.setIsRecommend(0);
        postsVo.setIsHot(0);
        postsVo.setStatus(1);
        postsVo.setAddTime(new Date());
        Integer insertId = postsService.save(postsVo);

        //todo 更新IP定位城市
        if (!("127.0.0.1").equals(ip)) {
            String city = BaiduIpUtil.getCity(ip);
            postsVo.setCity(city);
            postsService.update(postsVo);
        }

        //todo 保存图片
        if (insertId > 0 && null != imagesList && imagesList.size() > 0) {
            int i = 0;
            for (Object imgLink : imagesList) {
                String url = imgLink.toString();
                i++;
                PostsPictureVo postsPictureVo = new PostsPictureVo();
                postsPictureVo.setPostId(postsVo.getId());
                postsPictureVo.setPicUrl(url);
                postsPictureVo.setSortOrder(i);
                if (CheckUtil.checkSuffixFormat(url)) {
                    postsPictureVo.setUrlType(1);//1-图片
                } else {
                    postsPictureVo.setUrlType(2);//2-视频
                }
                if (videoCoverUrl != null) {
                    postsPictureVo.setVideoCoverUrl(videoCoverUrl);
                }
                postsPictureService.save(postsPictureVo);
            }
        }

        //todo 查询当前用户是否超过能获取积分的上限
        Boolean flag = userService.isUpperLimit(userId, "Post_Integral_Upper_Limit", IntegralType.POST_COMMENT_INTEGRAL_TYPE.getIndex());
        if (!flag) {
            //todo 记录积分情况
            UserIntegralVo userIntegralVo = new UserIntegralVo();
            userIntegralVo.setUserId(userId.intValue());
            userIntegralVo.setOrderId(postsVo.getId());
            //状态:1-增加；2-减少(即使用)
            userIntegralVo.setStatus(1);

            String postIntegral = macroService.queryValueByName("Post_Integral");
            if (!Validator.isNumber(postIntegral)) {
                postIntegral = "2";
            }
            //查询发帖能获取的值
            userIntegralVo.setIntegral(Integer.valueOf(postIntegral));
            IntegralType orderIntegralType = IntegralType.POST_INTEGRAL_TYPE;
            userIntegralVo.setRemark(orderIntegralType.getName());
            userIntegralVo.setIntegralType(orderIntegralType.getIndex());
            userIntegralVo.setAddTime(new Date());
            userIntegralService.save(userIntegralVo);
            //汇总用户目前积分
            userIntegralService.calUserCurrentPoints(userId, userIntegralVo.getStatus(), userIntegralVo.getIntegral());
            System.out.println("积分记录成功");
        }

        return detail(loginUser, postsVo.getId());
    }

    @RequestMapping(value = "detail", method = {RequestMethod.GET, RequestMethod.POST})
    public Object detail(@LoginUser UserVo loginUser,
                         @RequestParam("id") Integer id) {
        Long userId = loginUser.getUserId();

        PostsVo postsVo = postsService.queryObject(id);
        if (postsVo == null) {
            return toResponsFail("帖子不存在");
        }

        if (postsVo.getStatus() == 0) {
            return toResponsFail("帖子已被管理员禁止显示");
        }

        //todo 阅读数+1
        postsVo.setViewCount(postsVo.getViewCount() + 1);
        postsService.update(postsVo);

        //todo 处理emoji
        postsVo.setTitle(EmojiUtils.emojiRecovery2(postsVo.getTitle()));
        postsVo.setContentDesc(EmojiUtils.emojiRecovery2(postsVo.getContentDesc()));

        //todo 处理用户信息显示
        UserVo postsUserVo = userService.queryObject((long) postsVo.getUserId());
        postsVo.setUserInfo(postsUserVo);

        //todo 处理共有多少评论数
        Map<String, Object> para = new HashMap<>();
        para.put("postId", postsVo.getId());
        para.put("status", 1);
        para.put("sidx", "id");
        para.put("order", "desc");
        List<PostsCommentVo> postsCommentVos = postsCommentService.queryList(para);
        int commentCount = postsCommentVos.size();
        postsVo.setCommentCount(commentCount);

        //todo 处理相对时间显示
        postsVo.setRelativeDate(RelativeDateFormat.format(postsVo.getAddTime()));

        //todo 是否已经收藏
        Boolean collected = collectService.isCollected(2, postsVo.getId(), userId);
        if (collected) {
            postsVo.setIsCollected(1);
        }
        //todo 是否已经点赞
        Boolean liked = likeRecordService.isLiked(0, postsVo.getId(), userId);
        if (liked) {
            postsVo.setIsLiked(1);
        }

        //todo 图片/视频列表
        Map<String, Object> params = new HashMap<>();
        params.put("postId", id);
        params.put("sidx", "sort_order");
        params.put("order", "asc");
        List<PostsPictureVo> postsPictureVos = postsPictureService.queryList(params);
        postsVo.setPostsPictureVos(postsPictureVos);

        //todo 资源类型
        if (postsPictureVos.size() > 0) {
            PostsPictureVo postsPictureVo = postsPictureVos.get(0);
            postsVo.setResourceType(postsPictureVo.getUrlType());
        }

        return toResponsSuccess(postsVo);
    }

    @RequestMapping(value = "addComment", method = {RequestMethod.GET, RequestMethod.POST})
    public Object addComment(@LoginUser UserVo loginUser,
                             @RequestParam("postId") Integer postId,
                             @RequestParam("content") String content) throws UnsupportedEncodingException {

        Long userId = loginUser.getUserId();
        PostsVo postsVo = postsService.queryObject(postId);
        if (postsVo == null) {
            return toResponsFail("帖子不存在");
        }

        if (postsVo.getStatus() == 0) {
            return toResponsFail("帖子已被管理员禁止显示");
        }

        //评论内容长度拦截
        if (content.length() > 200) {
            return toResponsFail("评论内容不能超过200字符");
        }

        PostsCommentVo postsCommentVo = new PostsCommentVo();
        postsCommentVo.setUserId(userId.intValue());
        postsCommentVo.setPostId(postId);
        postsCommentVo.setContentDesc(EmojiUtils.emojiConvert1(content));
        //是否被管理员批准显示;1是;0未批准显示
        postsCommentVo.setStatus(1);
        postsCommentVo.setAddTime(new Date());
        postsCommentService.save(postsCommentVo);

        //todo 处理显示
        //相对时间
        postsCommentVo.setRelativeDate(RelativeDateFormat.format(postsCommentVo.getAddTime()));
        //评论者的信息
        UserVo commentUserVo = userService.queryObject((long) postsCommentVo.getUserId());
        postsCommentVo.setUserInfo(commentUserVo);
        //处理emoji
        postsCommentVo.setContentDesc(EmojiUtils.emojiRecovery2(postsCommentVo.getContentDesc()));

        //todo 记录积分情况
        UserIntegralVo userIntegralVo = new UserIntegralVo();
        userIntegralVo.setUserId(userId.intValue());
        userIntegralVo.setOrderId(postsVo.getId());
        //状态:1-增加；2-减少(即使用)
        userIntegralVo.setStatus(1);

        //todo 查询当前用户是否超过能获取积分的上限
        Boolean flag = userService.isUpperLimit(userId, "Post_Comment_Integral_Upper_Limit", IntegralType.POST_COMMENT_INTEGRAL_TYPE.getIndex());
        if (!flag) {
            //todo 查询发帖能获取的值
            String postIntegral = macroService.queryValueByName("Post_Comment_Integral");
            if (!Validator.isNumber(postIntegral)) {
                postIntegral = "1";
            }
            userIntegralVo.setIntegral(Integer.valueOf(postIntegral));
            IntegralType orderIntegralType = IntegralType.POST_COMMENT_INTEGRAL_TYPE;
            userIntegralVo.setRemark(orderIntegralType.getName());
            userIntegralVo.setIntegralType(orderIntegralType.getIndex());
            userIntegralVo.setAddTime(new Date());
            userIntegralService.save(userIntegralVo);
            //todo 汇总用户目前积分
            userIntegralService.calUserCurrentPoints(userId, userIntegralVo.getStatus(), userIntegralVo.getIntegral());
            System.out.println("积分记录成功");
        }


        return toResponsSuccess(postsCommentVo);
    }

    @IgnoreAuth
    @RequestMapping(value = "getCommentList", method = {RequestMethod.GET, RequestMethod.POST})
    public Object getCommentList(@RequestParam("postId") Integer postId,
                                 @RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "size", defaultValue = "10") Integer size) {

        PostsVo postsVo = postsService.queryObject(postId);
        if (postsVo == null) {
            return toResponsFail("帖子不存在");
        }

        if (postsVo.getStatus() == 0) {
            return toResponsFail("帖子已被管理员禁止显示");
        }

        //todo 处理所有评论
        Map<String, Object> param = new HashMap<>();
        param.put("page", page);
        param.put("limit", size);
        param.put("postId", postId);
        param.put("status", 1);
        param.put("sidx", "id");
        param.put("order", "desc");

        Query query = new Query(param);
        List<PostsCommentVo> postsCommentVos = postsCommentService.queryList(query);
        if (postsCommentVos.size() > 0) {
            for (PostsCommentVo postsCommentVo : postsCommentVos) {
                //相对时间
                postsCommentVo.setRelativeDate(RelativeDateFormat.format(postsCommentVo.getAddTime()));
                //评论者的信息
                UserVo commentUserVo = userService.queryObject((long) postsCommentVo.getUserId());
                postsCommentVo.setUserInfo(commentUserVo);
                //处理emoji
                postsCommentVo.setContentDesc(EmojiUtils.emojiRecovery2(postsCommentVo.getContentDesc()));
            }
        }

        int total = postsCommentService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(postsCommentVos, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }


}
